package com.xuecheng.filesystem.service;

import com.alibaba.fastjson.JSON;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.xuecheng.filesystem.dao.FileSystemRepository;
import com.xuecheng.framework.domain.filesystem.FileSystem;
import com.xuecheng.framework.domain.filesystem.response.FileSystemCode;
import com.xuecheng.framework.domain.filesystem.response.UploadFileResult;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author ShengJinFeng
 * @version V1.0
 * @ClassName UploadService
 * @Description (这里用一句话描述这个类的作用)
 * @date 2019/11/11 16:01
 * @since V1.0
 */
@Service
public class UploadService {

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FileSystemRepository fileSystemRepository;

    //private static final List<String> CONTENT_TYPES = Arrays.asList("image/jpeg","image/gif","image/png");

    private static final Logger LOGGER = LoggerFactory.getLogger(UploadService.class);

    /**
     * @Description 上传文件
     * @author ShengJinFeng
     * @date 2020/2/10
     */
    public UploadFileResult upload(MultipartFile file, String filetag, String businesskey, String metadata) {
        if (file == null){
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_FILEISNULL);
        }
        //上传文件到fastDFS,返回文件id
        String fileId = fdfsUpload(file);
        if (StringUtils.isEmpty(fileId)){
            ExceptionCast.cast(FileSystemCode.FS_UPLOADFILE_SERVERFAIL);
        }
        FileSystem fileSystem = new FileSystem();
        fileSystem.setFileId(fileId);
        fileSystem.setFilePath(fileId);
        fileSystem.setBusinesskey(businesskey);
        fileSystem.setFiletag(filetag);
        if (StringUtils.isNotEmpty(metadata)){
            try {
                Map map = JSON.parseObject(metadata, Map.class);
                fileSystem.setMetadata(map);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        fileSystem.setFileName(file.getOriginalFilename());
        fileSystem.setFileSize(file.getSize());
        fileSystem.setFileType(file.getContentType());
        fileSystemRepository.save(fileSystem);
        return new UploadFileResult(CommonCode.SUCCESS,fileSystem);
    }

    /**
     * @Description 上传文件到fastDFS,返回文件id
     * @author ShengJinFeng
     * @date 2019/11/11
     */
    private String fdfsUpload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        /*String contentType = file.getContentType();
        if (!CONTENT_TYPES.contains(contentType)){
            LOGGER.info("文件类型不合法，{}",originalFilename);
            return null;
        }*/
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null){
                LOGGER.info("文件内容不合法：{}",originalFilename);
                return null;
            }
            String ext = StringUtils.substringAfterLast(originalFilename, ".");
            synchronized (storageClient){
                StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
                return storePath.getFullPath();
            }
        }catch (Exception e){
            LOGGER.info("服务器内部错误"+originalFilename);
            e.printStackTrace();
            return null;
        }

    }
}
